package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SaveOwner
 */
//@WebServlet(description = "將指定的人員寫入DB", urlPatterns = { "/SaveOwner" })
public class SaveOwner extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SaveOwner() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		String strSQL = "";
		String returnResult ="OK";
		int tpid = Integer.parseInt(request.getParameter("tpid"));
		String mrid = request.getParameter("mrid");
		String er = request.getParameter("er");
		String[] owner = null;
		/** 若是測試計畫案，則不會有MRID的值 **/
		if ("tpOwner".equalsIgnoreCase(er)) {
			strSQL = "DELETE FROM tms_tpowner WHERE tpid=?";
			owner = request.getParameter("tpOwnerList").split(",");
		} else {
			strSQL = "DELETE FROM tms_mritem_tester WHERE tpid=? AND mrid=?";
			owner = request.getParameter("mrTesterList").split(",");
		}
		
		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, tpid);
			if ("tpOwner".equalsIgnoreCase(er)) {
				strSQL = "INSERT INTO tms_tpowner (tpid,userID) VALUES (?,?)";
			} else {
				ps.setString(2, mrid);
				strSQL = "INSERT INTO tms_mritem_tester (tpid,mrid,userID) VALUES (?,?,?)";	
			}
			ps.execute();
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, tpid);
			if ("tpOwner".equalsIgnoreCase(er)) {
				for(int i=0;i<owner.length;i++) {
					if (!owner[i].trim().equalsIgnoreCase("")) {
						owner[i] = owner[i].replace("<br/>","");
						ps.setString(2,owner[i]);
						ps.execute();
					}
				}
			} else {
				for(int i=0;i<owner.length;i++) {
					if (!owner[i].trim().equalsIgnoreCase("")) {
						owner[i] = owner[i].replace("<br/>","");
						ps.setString(2,mrid);
						ps.setString(3,owner[i]);
						ps.execute();
					}
				}
			}
		} catch (SQLException e) {
			returnResult = wid.keepErrorMes(conn, ps, e, "", true);
		} finally {
			try {
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				returnResult = e.toString();
				System.out.println(returnResult);
			}
		}
		response.setContentType("application/text");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(returnResult);	
	}

}
